package com.planw.beetl.sql.marker;

import com.intellij.codeInsight.daemon.RelatedItemLineMarkerInfo;
import com.intellij.codeInsight.daemon.RelatedItemLineMarkerProvider;
import com.intellij.codeInsight.navigation.NavigationGutterIconBuilder;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.markup.GutterIconRenderer;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiMethod;
import com.planw.beetl.service.BeetlMapperService;
import com.planw.beetl.service.BeetlSqlService;
import com.planw.beetl.utils.ConstUtil;
import com.planw.beetl.utils.ContextIcons;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
import org.jetbrains.annotations.NotNull;

public class BeetlSqlMarkdownLineMarkerProvider extends RelatedItemLineMarkerProvider {

  private static final Logger logger = Logger.getInstance(BeetlSqlMarkdownLineMarkerProvider.class);


  @Override
  protected void collectNavigationMarkers(@NotNull PsiElement element,
      @NotNull Collection<? super RelatedItemLineMarkerInfo<?>> result) {

    logger.info("调用Markdown增加跳转");
    if (!ConstUtil.isReady()) {
      logger.info("项目未准备完成");
      return;
    }
    if (!(element instanceof PsiFile)) {
      // 只处理整个文件
      return;
    }

    Project project = element.getProject();
    // 强制加载改变beetl不同版本的常量
    BeetlSqlService beetlSqlService = BeetlSqlService.getInstance(project);
    BeetlMapperService beetlMapperService = BeetlMapperService.getInstance(project);
    PsiFile mdFile = element.getContainingFile();
    PsiClass mapperClass = beetlSqlService.findMapperClass(mdFile);
    if (Objects.isNull(mapperClass)) {
      logger.info("无法对应Mapper类");
      return;
    }
    logger.info("对应Mapper类：" + mapperClass);
    Map<PsiMethod, PsiElement> methodAndSqlIdMap = beetlMapperService.getMethodAndSqlIdMap(mdFile,
        mapperClass, null);
    logger.info("与Mapper接口中所有方法的对应Map：" + methodAndSqlIdMap);
    String mapperClassName = mapperClass.getContainingFile().getName();
    Set<Entry<PsiMethod, PsiElement>> entrySet = methodAndSqlIdMap.entrySet();
    for (Entry<PsiMethod, PsiElement> entry : entrySet) {
      PsiMethod psiMethod = entry.getKey();
      PsiElement psiElement = entry.getValue();

      NavigationGutterIconBuilder<PsiElement> builder = NavigationGutterIconBuilder.create(
              ContextIcons.STATEMENT_LINE_MARKER_ICON).setAlignment(GutterIconRenderer.Alignment.CENTER)
          .setTargets(Collections.singleton(psiMethod))
          .setTooltipTitle("Navigation to " + psiMethod.getText() + " in " + mapperClassName);
      logger.info("创建md的" + psiElement + "内容与方法" + psiMethod + "名称的跳转图标");
      result.add(builder.createLineMarkerInfo(psiElement));
    }
  }

}
